package com.bwie.serverdemojdk17.config;

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2025/11/4 18:31
 */

@Configuration
// 扫描主数据源对应的Mapper接口（指定包路径，避免与第二个数据源冲突）
@MapperScan(
        basePackages = "com.bwie.serverdemojdk17.mapper.primary", // 主数据源的Mapper包
        sqlSessionFactoryRef = "primarySqlSessionFactory"
)
public class PrimaryDataSourceConfig {

    // 创建主数据源
    @Primary
    @Bean(name = "primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary") // 对应配置文件中的前缀
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    // 创建主数据源的事务管理器
    @Primary
    @Bean(name = "primaryTransactionManager")
    public DataSourceTransactionManager primaryTransactionManager(
            @Qualifier("primaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    // 创建主数据源的SqlSessionFactory（MyBatis专用）
    @Primary
    @Bean(name = "primarySqlSessionFactory")
    public MybatisSqlSessionFactoryBean primarySqlSessionFactory(
            @Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        // 若有MyBatis配置文件，可指定路径（如mapper.xml）
        // sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
        //     .getResources("classpath:mapper/primary/*.xml"));
        return sessionFactory;
    }
    
    /**
     * MyBatis-Plus配置
     */
    @Bean
    @Primary
    public ConfigurationCustomizer primaryConfigurationCustomizer() {
        return configuration -> {
            configuration.setMapUnderscoreToCamelCase(true);
        };
    }
}